package com.example.JRadioButton;

import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @Author 郅占伟
 * @ClassName MyJRadioButton
 * @Description TODO
 * @Date 2024年10月09日
 * @Version: 1.0
 */
public class MyJRadioButton extends JFrame {
    private ButtonGroup buttonGroup;    // 单选按钮组兑现
    private JPanel radioPanel;        // 放置三个JRadioButton按钮
    private JPanel colorPanel;      // 通过JRadioButton按钮切换背景颜色

    public MyJRadioButton() {
        colorPanel = new JPanel();
        this.add(colorPanel, BorderLayout.CENTER); // 将单选按钮放置在窗口中间

        radioPanel = new JPanel();
        buttonGroup = new ButtonGroup();

        // 创建三个JRadioButton按钮
        addJRadioButton("红色");
        addJRadioButton("黄色");
        addJRadioButton("蓝色");

        this.setLocation(500,300);
        this.add(radioPanel, BorderLayout.NORTH);
        this.setSize(1200, 900);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    /**
     * @description JRadioButton按钮的文本信息，用于创建一个带有文本信息的JRadioButton按钮,
     * 将该按钮添加到radioPanel面板和buttonGroup按钮组中，并添加监听器
     */
    private void addJRadioButton(String text) {
        JRadioButton radioButton = new JRadioButton(text);
        radioButton.setFont(new Font("微软雅黑", Font.PLAIN, 30));
        buttonGroup.add(radioButton);
        radioPanel.add(radioButton);
        radioButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Color color = null;
                if ("红色".equals(text)) {
                    color = Color.RED;
                } else if ("黄色".equals(text)){
                    color = Color.YELLOW;
                } else if ("蓝色".equals(text)){
                    color = Color.BLUE;
                }
                colorPanel.setBackground(color);
            }
        });
    }

}
